package com.ihr360.commons.request;

import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.util.StringUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * @author richey
 */
public abstract class AbstractIhr360PageSearchBody<T> implements Serializable {
    private static final String SORT_SEPERATOR = ",";

    protected int page;
    protected int size;
    protected String[] sort;
    protected boolean noPagination=false;

    public Pageable getPageable(){
        if (noPagination){
            this.page=0;
            this.size = Integer.MAX_VALUE;
        }
        /*if (this.page>0){
            this.page--;
        }*/
        if (sort!=null && sort.length>0){
            List<Sort.Order> orders = new ArrayList<>();
            for (String order:sort){
                if (StringUtils.isEmpty(order)){
                    continue;
                }
                String[] o= order.split(SORT_SEPERATOR);
                if (hasOrderDirection(o.length)){
                    orders.add(new Sort.Order(Sort.Direction.fromString(o[1]),o[0]));
                }else{
                    orders.add(new Sort.Order(Sort.Direction.ASC,o[0]));
                }
            }
            Sort pageSort = new Sort(orders);
            return new PageRequest(this.page,this.size,pageSort);
        }

        return new PageRequest(this.page,this.size);
    }


    private boolean hasOrderDirection(int len){
        return len==2? true:false;
    }


    public int getPage() {
        return page;
    }

    public void setPage(int page) {
        this.page = page;
    }

    public int getSize() {
        return size;
    }

    public void setSize(int size) {
        this.size = size;
    }

    public String[] getSort() {
        return sort;
    }

    public void setSort(String[] sort) {
        this.sort = sort;
    }

    public boolean isNoPagination() {
        return noPagination;
    }

    public void setNoPagination(boolean noPagination) {
        this.noPagination = noPagination;
    }
}
